package com.pandora.credit.mongo.service.impl;

import com.pandora.common.util.Constants;
import com.pandora.common.util.DateUtil;
import com.pandora.common.util.VerifyUtil;
import com.pandora.credit.dto.request.NewsRequest;
import com.pandora.credit.dto.response.LoanResponseNextInt;
import com.pandora.credit.mongo.dao.MongoNewsDao;
import com.pandora.credit.mongo.entity.MongoNews;
import com.pandora.credit.mongo.service.MongoNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author developer
 */
@Service
public class MongoNewsServiceImpl implements MongoNewsService {

    @Autowired
    private MongoNewsDao mongoNewsDao;

    @Override
    public List<MongoNews> queryAllLimit(int length) {
        return mongoNewsDao.selectAllLimit(length);
    }

    @Override
    public List<MongoNews> queryByIdLimit(long id, int length) {
        return mongoNewsDao.selectByIdLimit(id, length);
    }

    @Override
    public LoanResponseNextInt doGetNews(NewsRequest req, String ua) {
        String nextIdStr = req.getNextId();
        String lengthStr = req.getLength();
        int length = Constants.PAGE_LENGTH_DEFAULT;
        if(!VerifyUtil.isEmpty(lengthStr)){
            length = Integer.parseInt(lengthStr);
        }
        List<MongoNews> page = new LinkedList<MongoNews>();
        if(VerifyUtil.isEmpty(nextIdStr)){
            page = queryAllLimit(length+1);
        }else {
            page = queryByIdLimit(Long.parseLong(nextIdStr), length+1);
        }

        long reId = -1;
        if(page.size() > length){
            reId = page.get(page.size()-1).getId();
        }

        List<MongoNews.MongoNewsItem> reLi = new LinkedList<MongoNews.MongoNewsItem>();
        for(MongoNews mongoNews : page){
            if(mongoNews.getItem() == null){
                mongoNews.setItem(null);
            }
            mongoNews.getItem().setDate(DateUtil.getYMDPointDate(mongoNews.getCreatedTime()));
            reLi.add(mongoNews.getItem());
        }

        return new LoanResponseNextInt(Constants.RETURN_TYPE_NEWS,
                reLi,
                Integer.parseInt(String.valueOf(reId)));
    }
}
